// pages/goods/detail.js
import api from "../../api/api"
import util from "../../utils/util";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: '',
    imgPath: "/images",
    //显示规格弹窗
    showSpecPopup: false,
    bottomView:true,
    //步长量
    stepNum: 1,
    //最小值
    minNum: 1,
    date_img:false,   // 弹出后需要设置
    //最大值
    maxNum: 100,

    //显示优惠券弹窗
    showCouponPopup: false,

    //商品详情图片
    goodsImages: [],
    //商品标识
    id: '1',
    //价格
    price: '138.00',
    //名称
    name: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
    //标签图片
    tags: [''],
    //优惠券名称
    // couponName: '满200减20优惠',
    couponName: '',
    //优惠券标识
    couponId: '',
    //优惠券价钱
    couponPrice:0,
    //规格
    specification: '',
    //参数图片
    parameterImage: '',
    parameters: [],
    //商品详情图片
    detailImages: [],
    //购物车商品数量
    cartNum: '1',

    //类型
    goodsTypes: ["拉拉裤", "学习步裤"],
    //已选择类型
    selectedType: false,
    selectedType1: true,
    //已选择类型标识
    selectedTypeId: '',

    //商品类型,从数据库返回
    goods_type: '',

    //尺码
   // goodsSizes: ['NB', 'S', 'M', 'L', 'XL', '2XL', '3XL'],
    goodsSizes: [],
    //已选中尺码
    selectedSize: '',
    //已选中尺码标识
    selectedSizeId: '',

    goods_type_specs:'尺寸',

    //数量
    num: 1,

    //优惠券列表
    coupons: [],

    //规格组合价钱
    goods_spec_stock_list: {},

    //运费
    transportation_fee: 0,

    goodsImagesicon:'http://qnstatic.lianhequnmei.com/images/20221210/1.jpg',
    sp_zhiliao:true,
    sp_xuebu:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const util = require("../../utils/util")
    this.setData({
      imgPath: util.getImgPath()
    })

    //商品标识
    let goods_id = options.goods_id;
    this.setData({
      id: goods_id
    })
   
  },
  /**
   * 初始化测试数据
   */
  init() {
    const that = this;

    //购物车数量
    this.freshCart();

      const api = require("../../api/api");
      api.goods.detail({
        goods_id: that.data.id,
        success(res) {
  
          //提取数据到变量
          let data = res.data.data;
         //console.log('datadata',data);
          //商品图片
          that.data.goodsImages = data.head_images;
          that.setData({
            goodsImages: that.data.goodsImages,
            goodsImagesicon:that.data.goodsImages[0],
            goods_type_specs:data.goods_type_specs[0].name
          });
  
          if(data.goods_type == 300){
            that.setData({
              goodsImagesicon:'http://qnstatic.lianhequnmei.com/images/20221230/6db6c963f622b845fed14f2d464d13c.png'
            });
          }
  
          //价格
          that.setData({
            price: data.price
          })
  
          //名称
          that.setData({
            name: data.goods_name
          })
  
          //商品标签
          that.data.tags = [];
          that.data.tags.push(that.data.imgPath + '/icons/icons_tag.jpg')
          that.data.tags.push(that.data.imgPath + '/icons/icons_tag1.jpg')
          that.setData({
            tags: that.data.tags
          })
  
          //优惠券
          api.coupon.myCoupons({
            page: 1,
            page_size: 100,
            goods_type: data.goods_type,
            goods_price: data.price,
            filter_type: '2',
            success(resCoupon) {
  
              /*
              coupons: [{
                couponId: "1",
                couponName: "运费抵用卷",
                couponPrice: "30",
                endDate: "2010-11-7",
                ruleName: "每月订单可用",
                startDate: "2010-10-7",
              }
              */
              that.data.coupons = []
              for (const row of resCoupon.data.data.rows) {
                that.data.coupons.push({
                  couponId: row.coupon_id,
                  couponName: row.title,
                  couponPrice: row.price,
                  endDate: row.expire_time,
                  ruleName: row.alias_title,
                  startDate: row.start_use_time,
                })
              }
              that.setData({
                coupons: that.data.coupons
              })
  
              //如果只有一张优惠券，默认使用
              if(that.data.coupons.length==1){
                that.setData({
                  couponId:that.data.coupons[0].couponId,
                  couponName:that.data.coupons[0].couponName,
                  couponPrice:that.data.coupons[0].couponPrice,
  
                })
                // console.log("只有一张优惠券,couponId,couponName,couponPrice",that.data.couponId,that.data.couponName,that.data.couponPrice)
              }
            }
          })
  
          //规格
          //goodsTypes,类型
          if(data.goods_type == 200 ){
            that.data.goodsTypes = []
            for (const item of data.goods_type_specs[0].childs) {
              that.data.goodsTypes.push(item)
            }
            that.setData({
              goodsTypes: that.data.goodsTypes,
              
            })
          }
  
          //尺码,goodsSizes
          that.data.goodsSizes = []
          if(data.goods_type == 200 ){
            for (const item of data.goods_type_specs[0].childs) {
              that.data.goodsSizes.push(item)
            }
          }else if(data.goods_type == 300){
            for (const item of data.goods_type_specs[0].childs) {
              that.data.goodsSizes.push(item)
            }
          }
    
          that.setData({
            goodsSizes: that.data.goodsSizes,
          })
  
          //参数
          that.data.parameters = data.specifications;
          that.setData({
            parameters: that.data.parameters
          })
  
          //详情图片
          that.data.detailImages = data.detail_images
          that.setData({
            detailImages: that.data.detailImages
          })
  
          //规格组合价钱
          that.setData({
            goods_spec_stock_list: data.goods_spec_stock_list
          })
  
          //商品类型
          that.setData({
            //商品类型
            goods_type: data.goods_type,
          })
  
          //步长量
          if (data.goods_type == 300) {
  
            that.setData({
             //stepNum: 4,
             stepNum: 1,
             num: 1,
            //num:4,
            //minNum: 4,
            minNum: 1,
            maxNum: wx.getStorageSync('home').member_card_info.can_get_number
            })
  
          }
  
          //运费
          that.setData({
            transportation_fee: data.transportation_fee,
          })
  
        }
      })
  



    //商品图片
    // this.data.goodsImages = [];
    // this.data.goodsImages.push(this.data.imgPath + '/goods/goods.jpg');
    // this.data.goodsImages.push(this.data.imgPath + '/goods/goods.jpg');
    // this.setData({
    //   goodsImages: this.data.goodsImages
    // })

    //商品标签
    // this.data.tags = [];
    // this.data.tags.push(this.data.imgPath + '/goods/tag1.jpg')
    // this.data.tags.push(this.data.imgPath + '/goods/tag2.jpg')
    // this.setData({
    //   tags: this.data.tags
    // })

    // //参数图片
    // this.setData({
    //   parameterImage: this.data.imgPath + "/goods/parameter.jpg"
    // })

    // //详情图片
    // this.data.detailImages = []
    // this.data.detailImages.push(this.data.imgPath + "/goods/detail.jpg")
    // this.data.detailImages.push(this.data.imgPath + "/goods/detail.jpg")
    // this.setData({
    //   detailImages: this.data.detailImages
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
      //  初始化
      if(this.data.date_img) {
        this.setData({date_img:false})
      } else {  
        this.init();
      }
      
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {


  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onTabbarChange(event) {
    // console.log("onTabbarChange,event", event)
    this.setData({
      active: event.detail
    })
  },
  /**
   * 刷新购物车的信息
   */
  freshCart() {
    return;
    const that = this;
    const api = require("../../api/api")
    api.goods.cartList({
      success(res) {
        // console.log("cartList,res", res)
        that.setData({
          cartNum: res.data.data.rows.length
        })
      }
    })
  },
  /**
   * 加入购物车
   */
  addCart() {
    const that = this;

    //规格一定要选
    if(this.data.specification==""){
      // wx.showToast({
      //   title: '请先选规格',
      //   icon:'none',
      // })

      //弹出规格按钮
      this.setData({
        showSpecPopup:true,
      })
      return;
    }

    //关闭弹窗
    this.setData({
      showSpecPopup:false,
    })

    let goods_id=""+this.data.id+"#type:"+this.data.selectedTypeId+"#size:"+this.data.selectedSizeId;
   
    // return;

    // wx.showToast({
    //   title: '加入购物车',
    // })
    const api = require("../../api/api");
    api.goods.addCart({
      goods_id: goods_id,
      success(res) {
   
        if(res.data.code == 0){
          //取得购物车商品记录
          that.freshCart();
              wx.showToast({
               title: '加入购物车成功',
               icon:'none'
              })
        }
        

      }
    })
  },
    /**
   * 加入购物车
   */
  addCarts() {
    const that = this;

    //规格一定要选
    if(this.data.specification==""){
      wx.showToast({
        title: '请先选规格',
        icon:'none',
      })

      //弹出规格按钮
      this.setData({
        showSpecPopup:true,
      })
      return;
    }

    //关闭弹窗
    this.setData({
      showSpecPopup:false,
    })

    let goods_id=""+this.data.id+"#type:"+this.data.selectedTypeId+"#size:"+this.data.selectedSizeId;
   
    // return;

    // wx.showToast({
    //   title: '加入购物车',
    // })
    const api = require("../../api/api");
    api.goods.addCart({
      goods_id: goods_id,
      success(res) {

        if(res.data.code == 0){
          //取得购物车商品记录
          that.freshCart();
              wx.showToast({
               title: '加入购物车成功',
               icon:'none'
              })
        }

      }
    })
  },
  /**
   * 立即订购，下单
   */
  orderNow() {
    // wx.navigateTo({
    //   url: '/pages/orderSheet/paying',
    // })
    // this.setData({
    //   showSpecPopup:true,
    // })

    //规格
    if(this.data.specification==""){
      wx.showToast({
        title: '请选择规格',
      })
      return;
    }
    if(this.data.selectedSizeId==''){
      wx.showToast({
        title: '请选择尺码',
      })
      return;
    }

    let spec_stock_id = this.data.selectedSizeId; //this.data.selectedTypeId + ',' + this.data.selectedSizeId;

    let goodsdata = this.data.goods_spec_stock_list;

     
   if(this.data.goods_type == 300){
    let can_get_number = wx.getStorageSync('home').member_card_info.can_get_number;
    if (!goodsdata.hasOwnProperty(spec_stock_id)) { 
          wx.showToast({
            title: '商品没有该库存',
          })
          return;   
      } 
    if(can_get_number == 0){
      wx.showToast({
        title: '暂无领取箱数',
      })
      return;     
    }


   }

 

    // 商品信息
    let goods_info = [{
      //名称
      name: this.data.name,
      //单价
      price: this.data.price,
      //图片
      goodsImages: this.data.goodsImages,
      //规格
      spec: this.data.specification,

      //商品标识
      goods_id: this.data.id,
      //购买数量
      buy_number: this.data.num,
      //规格
      spec_stock_id: spec_stock_id,
      //商品类型
      goods_type: this.data.goods_type,
      //运费
      transportation_fee: this.data.transportation_fee,
    }];

    //价格
    let price = Number(this.data.price) * Number(this.data.num);

    //收货信息
    let receive_info = {
      receive_mobile: '',
      receive_name: '',
      receive_address: ''
    };

    //优惠券标识
    let coupon_id = this.data.couponId;

    //保存订单信息到本地
    let order = {
      //商品信息
      goods_info,
      //总价格
      price,
      //收货信息
      receive_info,
      //优惠券标识
      coupon_id,
      //优惠券名称
      couponName: this.data.couponName,
      //优惠券价钱
      couponPrice:this.data.couponPrice,

    }
  
    wx.setStorageSync('order', order);

    let orderReturn = wx.getStorageSync('order');

    //跳到结算页
    // wx.redirectTo({
    //   url: '/pages/orderSheet/orderSetling',
    // })
   wx.navigateTo({
      url: '/pages/orderSheet/orderSetling',
    })

    // api.order.transactions({
    //   goods_info: goods_info,
    //   //总价格
    //   price: price,
    //   //收货信息
    //   receive_info: receive_info,
    //   //优惠券标识
    //   coupon_id: this.data.couponId,
    //   success(res) {
    //     console.log("transactions,res", res)
    //   }
    // })
  },
  /**
   * 选规格
   */
  selSpec() {
    this.setData({
      showSpecPopup: true
    })
  },
  /**
   * 关闭规格弹出窗
   */
  onSpecPopupClose() {

 
    this.setData({
      showSpecPopup: false,
    })
  },
  /**
   * 选择类型
   * @param {*} e 
   */
  selType(e) {
     
    // let t = e.currentTarget.dataset.name;
    // let id = e.currentTarget.dataset.id;

    let type = e.currentTarget.dataset.type;
    let that = this;

    if(type == 'xuebu'){

      that.setData({
        selectedType:type,
        selectedType1:'',
        sp_xuebu:true,
        sp_zhiliao:false,
        goodsImagesicon:'http://qnstatic.lianhequnmei.com/images/20221230/6271b4d3c67e7bc0f6d47bfd38f798a.png'
      });

    }else if(type == 'zhiniao'){
      that.setData({
        selectedType:'',
        selectedType1:type,
        sp_zhiliao:true,
        sp_xuebu:false,
        goodsImagesicon:'http://qnstatic.lianhequnmei.com/images/20221230/6db6c963f622b845fed14f2d464d13c.png'
      });
    }
    // this.setData({
    //   selectedType: t,
    //   selectedTypeId: id,
    //   specification: t+"/"+this.data.selSize + '码',
    //   specification: t,
    // })
    
    //  if(t == '学步裤'){
    //    this.data.goodsImages[0] = 'http://qnstatic.lianhequnmei.com/images/20221119/2.jpg';
    //    this.setData({
    //     goodsImages:this.data.goodsImages
    //    });
    //  }else{
    //   this.data.goodsImages[0] = 'http://qnstatic.lianhequnmei.com/images/20221210/1.jpg';
    //   this.setData({
    //     goodsImages:this.data.goodsImages
    //    });
    //  }
     
    //重算价钱
    this.reCalPrice();
  },
  /**
   * 选择尺寸
   */
  selSize(e) {
  
    let t = e.currentTarget.dataset.name;
    let id = e.currentTarget.dataset.id;
    let img = e.currentTarget.dataset.img;

    
    console.log('imgss',img);

    this.setData({
      selectedSize: t,
      specification: t,//this.data.selectedType+" "+t + '',
      selectedSizeId: id,
      goodsImagesicon:img,
    })



    //重算价钱
    this.reCalPrice();
  },
  /**
   * 重算价钱
   */
  reCalPrice() {
    let key = '' + this.data.selectedTypeId + "," + this.data.selectedSizeId;
   // let stock = this.data.goods_spec_stock_list[key];
   let stock = this.data.goods_spec_stock_list[this.data.selectedSizeId];

   // console.log('pricessssws',stock);
   // console.log('this.data.selectedSizeId',this.data.selectedSizeId);

    if (stock) {
      this.setData({
        price: stock.price
      })
    }
  },
  /**
   * 改变数量事件
   * @param {object} e 
   */
  onNumChange(e) {
    this.setData({
      num: e.detail
    })
  },
  onCouponPopupClose() {
    this.setData({
      showCouponPopup: false
    })
  },
  showCouponWin() {
    this.setData({
      showCouponPopup: true
    })
  },
    //预览图片，放大预览
    preview(event) {
      console.log(event.currentTarget.dataset.src)
      let currentUrl = event.currentTarget.dataset.src;

      this.setData({
        date_img:true,
      });
      
      wx.previewImage({
        current: currentUrl, // 当前显示图片的http链接
        urls: [this.data.goodsImagesicon]   // 需要预览的图片http链接列表
      })
    },
  /**
   * 使用优惠券
   * @param {*} e 
   */
  usingCoupon(e) {
    // console.log("usingCoupon", e)
    //优惠卡标识
    let id = e.currentTarget.dataset.id;
    //名称
    let name = e.currentTarget.dataset.name;
    //价钱
    let price=e.currentTarget.dataset.price;

    this.setData({
      couponId: id,
      couponName: name,
      couponPrice:price,
    });

    //关闭弹窗
    this.setData({
      showCouponPopup: false
    })
  },
  closeCouponPopup(e) {
    this.setData({
      showCouponPopup: false
    })
  },
  /**
   * 购物车
   */
  gotoCart() {
    wx.navigateTo({
      url: '/pages/cart/index',
    })
  },
  /**
   * 客服
   */
  customerService() {
    let ids = this.data.id;
    //写入回调地址
    wx.setStorageSync('im:redirectUrl', "/pages/goods/detail?goods_id="+ids)
    wx.navigateTo({
      url: '/im/pages/index?type=kefu',
    })
  },
  /**
   * 立即下单
   */
  buyNow(){
    this.setData({
      showSpecPopup:true,
    })
  },
  closeSpuPopup(){
    this.setData({
      showSpecPopup:false,
    })
  }
})